package zw_1_100.zw_8_字符串转换整数;

class Solution {

    public static void main(String[] args) {
        String s = "4193 with words";
        int atoi = myAtoi(s);
        System.out.println(atoi);
    }

    public static int myAtoi(String s) {
        char[] chars = s.toCharArray();
        int len = chars.length;
        //1.去空格
        int index = 0;
        while (index < len && chars[index] == ' ')
            index++;
        //2.排除极端情况 "    "
        if (index == len) return 0;
        //3.设置符号
        int sign = 1;
        char firstChar = chars[index];
        if (firstChar == '-') {
            index++;
            sign = -1;
        } else if (firstChar == '+') {
            index++;
        }
        int res = 0, last = 0; //last 记录上一次的res，以此来判断是否溢出
        while (index < len){
            char c = chars[index];
            if (c < '0' || c > '9') break;
            last = res;
            res = 10 * res + (c - '0');
            if (last != res/10){
                return (sign == (-1)) ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }
            index++;
        }
        return res * sign;
    }
}
